from flask import Flask, render_template, request, jsonify
import datetime
import os

app = Flask(__name__)

# 用于存储已提交数据的IP地址
submitted_ips = set()

# 检查IP是否已提交过
def is_ip_submitted(ip):
    return ip in submitted_ips

# 将数据保存到txt文件中
def save_to_file(name, ip, timestamp):
    with open('submissions.txt', 'a') as file:
        file.write(f'Name: {name}, IP: {ip}, Time: {timestamp}\n')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form.get('name')
        ip = request.remote_addr
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        if is_ip_submitted(ip):
            return jsonify({'error': 'You have already submitted.'}), 400
        
        save_to_file(name, ip, timestamp)
        submitted_ips.add(ip)
        return jsonify({'success': 'Your name has been submitted successfully.'}), 200
    
    return render_template('index.html')

if __name__ == '__main__':
    # 确保应用启动时清空已提交的IP集合（仅用于开发环境）
    submitted_ips.clear()
    app.run(debug=True)